package com.example.comic.mvp.view

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.comic.R
import com.example.comic.mvp.model.snackbar
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_page.*
import java.lang.Exception

class PageFragment : Fragment() {
    lateinit var link: String

    companion object {
        const val INTENT_LINK = "link"
        fun newInstance(link: String): PageFragment {
            val b = Bundle()
            b.putString(INTENT_LINK, link)
            val fragment = PageFragment()
            fragment.arguments = b
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_page, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        progressBar.visibility = View.VISIBLE
        link = arguments!!.getString(INTENT_LINK)
    }

    override fun onResume() {
        super.onResume()
        Picasso.get().load(link).into(imageView, object : Callback {
            override fun onSuccess() {
                progressBar.visibility = View.GONE
            }

            override fun onError(e: Exception?) {
                progressBar.visibility = View.GONE
                imageView.snackbar(R.string.network_error)
            }
        })
    }
}